﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using WebApp.Models;

namespace WebApp.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ProductsController : ControllerBase
    {
        private DataContext dbContext;

        public ProductsController(DataContext dbContext)
        {
            this.dbContext = dbContext;
        }

        // Get products
        [HttpGet]
        public IEnumerable<Product> GetProducts()
        {
            return dbContext.Products;
        }

        // Get product by Id
        [HttpGet("{id}")]
        public Product GetProduct()
        {
            return dbContext.Products.FirstOrDefault();
        }

        // Create product
        [HttpPost]
        public void AddProduct([FromBody]ProductBinding p)
        {
            dbContext.Products.Add(p.ToProudct());
            dbContext.SaveChanges();
        }

        // Modify product
        [HttpPut]
        public void UpdateProduct([FromBody] Product p)
        {
            dbContext.Products.Update(p);
            dbContext.SaveChanges();
        }

        [HttpDelete("{id}")]
        public void DeleteProduct(long id)
        {
            dbContext.Products.Remove(new Product { ProductId = id });
            dbContext.SaveChanges();
        }
    }
}
